#include "../../util/Trace.hpp"
#include "../../util/poll_set.hpp"
#include "../../transport/transport_udp.hpp"


#include <boost/make_shared.hpp>
#include <boost/smart_ptr.hpp>
#include <memory>
#include <unistd.h>


bool UDP_write(TransportUDPPtr transport, boost::shared_array<uint8_t>& buffer, uint32_t size)
{


	buffer;
	uint32_t write_size = size;
	uint32_t write_sent = 0;
	bool has_write_callback = true;

	//writeUDPTransport();
	bool writing = true;
	bool can_write_more = true;


	transport->enableWrite();
	while(has_write_callback && can_write_more)
	{


		uint32_t to_write = write_size - write_sent;	
		//ROS_DEBUG_NAMED("superdebug", "Connection Client Writing %d bytes", to_write);
		TRACE("[INFO] superdebug Connection Client Writing %d bytes", to_write);
		uint32_t bytes_sent = transport->write(buffer.get()+write_sent, to_write);
		//ROS_DEBUG_NAMED("superdebug", "Connection Client Wrote %d bytes", bytes_sent);
		TRACE("[INFO] superdebug Connection Client Wrote %d bytes", bytes_sent);
		TRACE("[INFO] superdebug Connection Client total Wrote %d bytes", write_sent);


		if(bytes_sent<0)
		{
			writing = false;
			return false;	
		}
		write_sent += bytes_sent;

		if(bytes_sent < (int)write_size - (int)write_sent)
		{
			can_write_more = false;	
		}

		if(write_sent == write_size)
		{
			//buffer.reset();
			write_sent = 0;
			write_size = 0;
			has_write_callback = 0;	
			 
		}
	}

	if(!has_write_callback)
	{
		transport->disableWrite();	
	}
//	buffer.reset();
	writing = false;

	return true;
}

//void UDP_write(boost::shared_array<uint8_t>& buffer, uint32_t size)
int main(int argc, char *argv[])
{
    //控制台输出 hello world
    TRACE("[INFO] hello world!");


    TRACE("[INFO] create udp_transport...");

    PollSet poll_set;
    TransportUDPPtr udp_transport; 
    udp_transport = std::make_shared<TransportUDP>(&poll_set);
    TRACE("[INFO] ok!");


    //Server: createIncoming
    //Client: connect
	
	//udp port: 9090-10000



	//write
    
    int cnt = 0;

	uint8_t tmp[20] = "Hello World:";
	boost::shared_array<uint8_t> buffer(tmp);

    	TRACE("[INFO] create connection...");
		//udp_transport->connect("82.157.129.44", 9090, 300);
		udp_transport->connect("127.0.0.1", 9090, 300);
    	TRACE("[INFO] ok!");

	while(true)
	{
		//buffer.reset();
		//buffer = boost::shared_array<uint8_t>(tmp);


        //create buffer
        buffer[12]='0'+(cnt++);
        buffer[13]=0;
        int size = 13;

        TRACE("[DEBUG] buffer:%s, size:%d", buffer.get(), size);


 	 	if(UDP_write(udp_transport, buffer, size)==false)
		{
			TRACE("[INFO] UDP_write failed!");
			break;
		}

	
        //0.2s, 200 ms, 200 000 us
        usleep(200000);
	}
	


//-----------NOTE: UDP_write()


    return 0;
}
